<template>
    <div>
        <!-- <button @click="clearit();">清除cookie</button>-->

        <div :class='{"edit-component-container":!onTop,"edit-component-container-top":onTop}'>
            <div>{{testinfo}}</div>
            <div class="edit-component-face">
                <img  v-lazy="{src:jsonParsehurl(edit_user),error: errimg, loading:errimg}"
                      :key="edit_user"/>
            </div>
            <div class="edit-component-box">
                <div class="edit-component-box-img" v-show="!is_edit">
                    <img src="../assets/images/pencil.png"/>
                </div>
                <div class="edit-component-box-txt">
                <textarea v-reset-page placeholder="我也要说两句" name="msg" @focus="msgAct(true)" @blur="msgAct(false)" :rows="rows"
                          v-model="msg"></textarea>
                </div>
                <div class="edit-component-box-btn" v-show="is_edit" @click="butelSendSimpleTopicMsg();">发表</div>
                <div class="clearBoth"></div>
            </div>
            <div class="clearBoth"></div>
        </div>

        <!-- 如果有评论:加载评论数据 -->
        <ul class="remark-new-component-list" v-if="!hasNoComment">
            <li class="remark-new-component-item" v-for="msg in historyComment" :key="historyComment.timestamp">
                <!-- 用户头像、时间、用户昵称、内容 -->
                <div class="remark-new-component-face">
                    <!-- <img v-if="jsonParsehurl(msg.sender_extra_info)" v-lazy="jsonParsehurl(msg.sender_extra_info)" />
                     <img v-else src="../assets/images/user.png" />-->
                    <img v-lazy="{src:jsonParsehurl(msg.sender.extinfo),error: errimg, loading:errimg}"
                         :key="msg.sender.extinfo"/>
                </div>
                <div class="remark-new-component-info">
                    <div class="remark-new-component-title">
                        <a href="Javascript:;">{{msg.sender.nickname}}</a>
                        <span>&nbsp;&nbsp; {{toRemarkTime(Math.round(msg.timestamp/1000))}}</span>
                    </div>
                    <div class="remark-new-component-content" :class="{'c_orange':msg.msgtype=='imhb','info_org':msg.msgtype=='imreward'}" v-if="msg.msgtype!='imhb'||jsonParse(msg.context).a_stype!='send'" v-html="msg.content"></div>
                    <div class="remark-new-component-content" v-if="msg.msgtype=='imhb'&&jsonParse(msg.context).a_stype=='send'">
                        <div class="remark-new-hb" @click="callApp">
                            <div class="remark-new-hb-top">
                                <img src="../assets/images/redbag_yellow.png" class="hb_icon">
                                <div class="hb_disc">{{jsonParse(msg.context).a_data.bb_content}}</div>
                                <div class="hb_get">领取红包</div>
                            </div>
                            <div class="remark-new-hb-bottom">
                                红包
                            </div>
                        </div>

                    </div>
                </div>
                <div class="clearBoth"></div>
            </li>
        </ul>
        <div class="remark-new-component-blank" v-else-if="hasNoComment">
            <img v-lazy="defaultimg"/>
        </div>

        <!--<div class="edit-component-takeup"></div>-->
    </div>
</template>

<script>
    export default {
        props: {
            topicid: {
                type: String,
                default: ""
            },
            reportData: {
                type: Object,
                default: function () {
                    return {};
                }
            },
            onTop: {
                type: Boolean,
                default: false
            },
            comtype:{
                type:String,
                default:""
            },
            isRealtime:{
                type:Boolean,
                default:true
            },
            wakeupParam: {
                type: Object,
                default: function () {
                    return {
                        contentType: 6,
                        contentParam: "",
                        infoParams: {}
                    }
                }
            }
        },
        data: function () {
            return {
                defaultimg:require("../assets/images/nocomment.png"),
                edit_user:require("../assets/images/anonymous.png"),
                sendmsgid:"",
                sendmsg:{},
                errimg: require("../assets/images/user.png"),
                lasttmp: 0,
                total: 0,
                // 用户信息接口
                authUrl: location.protocol + process.env.VUE_APP_UC_URL,
                authUserInfo: {},
                access_token: this.GetCookie("access_token"),
                openid: this.GetCookie("openid"),
                rows: 1,
                is_edit: false,
                msg: "",
                testinfo: "",
//                reportdata: {},     // 上报用户行为的数据
                hasNoComment: false,
                historyComment: [],
                msghisArrayTmp: [],
                imEndTime: 0,
                appkey: "",// 新评论系统的appkey
                appsecret: "",// 新评论系统的企业秘钥
                paasImServerUrl: "",// 新评论系统地址
            }
        },
        mounted: function () {
            $(".remark-new-component-blank img").on('click',function(e){
                e.peventDefalut();
            })
            if (this.access_token == 'update' || this.openid == 'update') {
                if (this.getUrlParam("access_token") != null && this.getUrlParam("openid") != null) {
                    this.access_token = this.getUrlParam("access_token");
                    this.openid = this.getUrlParam("openid");
                    this.SetCookie("access_token", this.getUrlParam("access_token"), 1);
                    this.SetCookie("openid", this.getUrlParam("openid"), 1);
                } else {
                    this.access_token = "";
                    this.openid = "";
                }
            }

            // 页面加载完毕，执行getComment方法
            this.getComment();

        },
        methods: {

            /*  clearit:function(){
                   this.ClearCookie("access_token");
                   this.ClearCookie("openid");
                   this.ClearCookie("YF_USER_INFO");
                   this.ClearCookie("YF_USER");
               },*/
            // 获取评论信息
            getComment: function () {
                if(this.$route.name=="Live"){
                    if($(".fixedBottom").is(':hidden')){
                        $(".edit-component-container").css("bottom","0");
                        $(".edit-takeup").css("height","3.8rem");
                        $("#live_hall_container").css("padding-bottom","0");
                    }
                }

                let that = this;
                let userCoo = that.GetCookie("YF_USER_INFO");
                if(userCoo!=""&&userCoo!=null&&typeof (userCoo)!="undefined"){
                    that.edit_user=JSON.parse(userCoo).face;
                }
                // 获取授权信息
                function getAuthorizeUserInfo(access_token, openid) {
                    let requestUrl = that.authUrl + "/user/info?access_token=" + access_token + "&openid=" + openid;
                    // alert("access_token:" + access_token + ";openid:" + openid);

                    that.axios.get(requestUrl).then((response) => {
                        let res = response.data;
                        if (res.code === 0) {
                            that.authUserInfo={
                                uid: res.user.id,
                                nickname: res.user.nickname,
                                faceurl: res.user.face,
                                extinfo:JSON.stringify({
                                    hdurl: res.user.face
                                })
                            }
                            that.SetCookie("YF_USER_INFO", JSON.stringify(res.user), 1);
                            that.edit_user=that.authUserInfo.faceurl;
                        } else {
                            that.ClearCookie("access_token");
                            that.ClearCookie("openid");
                            console.error("获取用户信息失败：code=" + res.code);
                        }
                    });
                }
                that.axios.get(
                   /* "https://yfhefei.butel.com:44335/setsail/external/externalService?service=getcommnetsys"*/
                interbaseUrl
                + "setsail/external/externalService?service=getcommnetsys"
                ).then((response) => {
                    if (response.data.state == 1000) {
                        that.appkey = response.data.data.appkey;
                        that.appsecret = response.data.data.appsecret;
                        that.paasImServerUrl = response.data.data.paasImServerUrl;
                        PaaSWebIM.setOptions({
                            paasimHost: that.paasImServerUrl,
                            appkey: that.appkey,
                            appsecret: that.appsecret
                        });
                        // 用户登录
                        if (userCoo == '' || userCoo == null) {
                            if(that.access_token==""||that.openid==""||that.access_token==null||that.openid==null){

                            } else {
                                getAuthorizeUserInfo(that.access_token, that.openid);
                            }
                            // 执行userLogin方法后，将进入请求回调函数
                        }else{
                            let userCooJson =JSON.parse(that.GetCookie("YF_USER_INFO"));
                            that.authUserInfo={
                                uid:userCooJson.id,
                                nickname:userCooJson.nickname,
                                faceurl:userCooJson.face,
                                extinfo:JSON.stringify({
                                    hdurl:userCooJson.face
                                })
                            }
                            that.edit_user=that.authUserInfo.faceurl;
                        }
                        if(that.isRealtime){
                            imLogin();
                        }else{
                            joinBigGroupOK();
                        }

                    }
                });

                // 登录群组
                function imLogin() {
                    let imUserInfo = {};
                    if (userCoo != '' && userCoo != null){
                        let userCooJson=JSON.parse(userCoo);
                        that.authUserInfo={
                            uid:userCooJson.id,
                            nickname:userCooJson.nickname,
                            faceurl:userCooJson.face,
                            extinfo:JSON.stringify({
                                hdurl:userCooJson.face
                            })
                        }
                        imUserInfo={};
                    }

                    //注意每个数字代表的含义，比如，
                    //1表示监听申请加群消息，2表示监听申请加群被同意消息，3表示监听申请加群被拒绝消息等
                    var onGroupSystemNotifys = {};

                    var imListeners = {
                        "jsonpCallback": jsonpCallback, //IE9(含)以下浏览器用到的jsonp回调函数,移动端可不填，pc端必填
                        "onBigGroupMsgNotify": onBigGroupMsgNotify, //监听新消息(大群)事件，必填
                        "onMsgNotify": onMsgNotify,//监听新消息(私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息)事件，必填
                        "onGroupSystemNotifys": onGroupSystemNotifys, //监听（多终端同步）群系统消息事件，必填
                    }
                    //登录IM 获取实时消息
                    var imOptions = {
                        'isAccessFormalEnv': true,//是否访问正式环境，默认访问正式，选填
                        'isLogOn': true//是否开启控制台打印日志,默认开启，选填
                    };
                    //    alert("imUserInfo:"+JSON.stringify(imUserInfo))
                    PaaSWebIM.login(imUserInfo, imListeners, imOptions, loginOK, loginErr);
                }

                function jsonpCallback(rspData) {
                    //设置接口返回的数据
                    PaaSWebIM.setJsonpLastRspData(rspData);
                }

                function onBigGroupMsgNotify(msgList) {
                    setTimeout(function(){
                        if (!msgList || msgList.length == 0) {
                            return;
                        }
                        let newmsg=JSON.parse(msgList[0].elems[0].content.data);
                        let ifadd=1;
                        for(let i=0;i<that.historyComment.length;i++){
                            if(newmsg.msgid==that.historyComment[i].msgid){
                                ifadd=0;
                                break;
                            }
                        }
                        if(ifadd==1){
                            that.hasNoComment=false;
                            let newarr=that.historyComment;
                            newarr.push(newmsg);
                            that.historyComment=[];
                            setTimeout(function () {
                                that.historyComment=newarr;
                            },100)
                        }
                    },200)
                }

                function onMsgNotify(newMsgList) {

                }

                function loginOK() {
                    console.log("登录成功");
                    console.log("topcid"+that.topicid)
                    PaaSWebIM.applyJoinBigGroup(that.topicid, joinBigGroupOK, joinBigGroupErr);
                }

                function loginErr(data) {
                    console.log("登录失败");
                    console.log(JSON.stringify(data,undefined,2))
                }

                // 加入大群成功后获取历史消息
                function joinBigGroupOK(data) {
                    console.log("加入大群成功");
                    //获取历史消息
                    var getMessageParams = {
                        "topicid": that.topicid,
                        "pagesize": 20,
                        "ascsort": true
                    }
                    //  console.log(getMessageParams)
                    PaaSWebIM.butelPaasGetHismessage(getMessageParams, that.appkey, that.appsecret, onSuccgetPaasHistoryMsg, onFailgetPaasHistoryMsg);
                }

                function onSuccgetPaasHistoryMsg(data) {
                    console.log('获取历史消息成功----------------------');
                     console.log(JSON.stringify( data.pagingrows.rows));

                    that.historyComment = data.pagingrows.rows;
                    if(data.pagingrows.rows.length==0){
                        that.hasNoComment=true;
                    }
                    setTimeout(function(){
                        $("#my_video_window_bottom").scrollTop($("#live_chat_container").height());
                    },200)

                    //  console.log(JSON.stringify(that.historyComment,undefined,2));
                }

                function onFailgetPaasHistoryMsg(data) {
                    console.log(JSON.stringify(data,undefined,2))
                    console.log('获取历史消息失败');
                }

                function joinBigGroupErr(data) {
                    console.log(JSON.stringify(data))
                    console.log("加入大群失败");
                }



            },

            /** 输入框部分 */
            // 激活输入框事件
            msgAct: function (state) {
                let that = this;
                that.is_edit = state;
                if (that.is_edit) {
                    that.rows = 3;
                    if ((that.access_token == null || that.openid == null||that.access_token==''||that.openid == '')
                        && (that.GetCookie("YF_USER_INFO") == null || that.GetCookie("YF_USER_INFO") == ''
                            ||typeof (that.GetCookie("YF_USER_INFO"))=="undefined")) {

                        that.$dialog.confirm('登录评论需刷新页面，确定登录并评论吗？',{
                            okText: '确定',  // 本地化确认按钮文字提示内容
                            cancelText: '取消',  //本地化关闭按钮文字提示内容
                        }).then(function () {
                            // 点击确定执行
                            document.getElementsByTagName("textarea")[0].blur();
                            // 用户未登录，跳转登陆页
                            that.openAuthorizePage();
                        })
                            .catch(function () {
                                // 点击取消执行
                                document.getElementsByTagName("textarea")[0].blur();
                                return false;
                            });
                    }
                } else {
                    that.rows = 1;
                }
            },

            // 跳转授权页面
            openAuthorizePage: function () {
                this.SetCookie("access_token", "update", 1 / 24 / 6);
                this.SetCookie("openid", "update", 1 / 24 / 6);
                let authUrl = this.authUrl + "v1/oauth2/web/otherAuthorize";
                let url = location.protocol + '//' + location.host + location.pathname;
                location.href = authUrl + "?redirect_uri=" + escape(url);
            },

            // 发送消息
            butelSendSimpleTopicMsg: function () {

                let that = this;
                let userCoo = that.GetCookie("YF_USER_INFO");
                function onsuc(data){
                    let mess= data.pagingrows.rows;
                    let addmess=[];
                    if(that.historyComment.length!=0){
                        let mid=that.historyComment[0].msgid;
                        for(let j=0;j<mess.length;j++){
                            if(mess[j].msgid!=mid){
                                if(mess[j].msgid!=that.sendmsgid){
                                    addmess.push(mess[j])
                                }
                            }else {
                                break;
                            }
                        }
                        addmess.push(sendmsg);
                        let newarr=that.historyComment.concat(addmess);
                        that.historyComment=[];
                        setTimeout(function () {
                            that.historyComment=newarr;
                            setTimeout(function(){
                                $("#my_video_window_bottom").scrollTop($("#live_chat_container").height());
                            },200);
                        },100)
                    }else{
                        let addmess=[];
                        let mess= data.pagingrows.rows;
                        for(let j=0;j<mess.length;j++){
                            if(mess[j].msgid!=that.sendmsgid){
                                addmess.push(mess[j])
                            }
                        }
                        addmess.push(sendmsg);
                        that.historyComment=addmess;
                        setTimeout(function(){
                            $("#my_video_window_bottom").scrollTop($("#live_chat_container").height());
                        },200);
                    }
                }
                function onfalse(){

                }

                function cbErr(){
                   /* alert("消息发送失败");*/
                }
                function cbOK(data){
                    that.hasNoComment=false;
                    that.sendmsgid=data.result.msgid;
                    that.sendmsg=data.reqparams;
                    that.sendmsg.timestamp=new Date().getTime();
                    that.sendmsg.msgid=that.sendmsgid;
                   /* alert("消息发送成功");*/
                    that.msg = "";
                    if(!that.isRealtime){
                        let getMessageParams2 = {
                            "topicid": that.topicid,
                            "pagesize": 20,
                            "ascsort": false
                        }
                        let arr=that.historyComment;
                        arr.push(that.sendmsg)
                        that.historyComment=[];
                        setTimeout(function () {
                            that.historyComment=arr;
                        },100)
                        PaaSWebIM.butelPaasGetHismessage(getMessageParams2, that.appkey, that.appsecret, onsuc, onfalse);
                    }else{
                        let arr=that.historyComment;
                        arr.push(that.sendmsg)
                        that.historyComment=[];
                        setTimeout(function () {
                            that.historyComment=arr;
                            setTimeout(function(){
                                $("#my_video_window_bottom").scrollTop($("#live_chat_container").height());
                            },200);
                        },100)

                    }
                }


                if (userCoo == '' || userCoo == null) {
                    alert("未登录用户不能发表评论！");
                } else {
                    let sData = {
                        topicid: that.topicid,
                        title: "",
                        content: that.msg,
                        context:"",
                        parentid:"",
                        sender:that.authUserInfo,
                        msgtype:"text2",
                        acc:"",
                        businesstype:that.comtype,
                    };
                    //  alert("butelSendSimpleTopicMsg请求参数：" + JSON.stringify(sData));
                    PaaSWebIM.butelPaasSendmessage(sData, that.appkey, that.appsecret,cbOK,cbErr)
                }

            },
            callApp: function () {
                let that=this;
                that.$dialog.confirm('该活动需要打开【扬帆】app后参与，确认打开参与吗？',{
                    okText: '确定',  // 本地化确认按钮文字提示内容
                    cancelText: '取消',  //本地化关闭按钮文字提示内容
                })
                    .then(function () {
                        // 点击确定执行
                        openDownPage(that.wakeupParam.contentType, that.wakeupParam.contentParam, that.wakeupParam.infoParams);
                    })
                    .catch(function () {
                        // 点击取消执行
                    });


            },
        }
    }
</script>

<style>
    .remark-new-component-list a,
    .remark-new-component-list a:link,
    .remark-new-component-list a:visited {
        color: #459AF5;
        text-decoration: none;
    }

    .remark-new-component-list {
        padding: 0;
        margin: 0 auto;
    }

    .remark-new-component-item {
        margin: 0.6rem auto;
        position: relative;
        padding-left: 40px;
    }

    .remark-new-component-face {
        width: 32px;
        position: absolute;
        left: 0;
        top: 5px;
    }

    .remark-new-component-face img {
        width: 32px;
        height: 32px;
        border-radius: 50%;
    }

    .remark-new-component-info {
        width: 100%;
    }

    .remark-new-component-content {
        line-height: 1.8rem;
    }

    .remark-new-component-title {
        font-size: 0.9rem;
        color: #999999;
    }

    .remark-new-component-title {
        line-height: 1.8rem;
    }

    .remark-new-component-title a, .remark-new-component-title a:link, .remark-new-component-title a:visited {
        color: #459AF5;
        text-decoration: none;
    }

    .remark-new-component-content {
        font-size: 1.0rem;
        color: #666666;
    }

    .remark-new-component-time {
        margin: 0
    }

    .remark-new-component-name {
        margin: 0;
        color: #459AF5;
    }

    .remark-new-component-content-pic {
        width: 100%;
    }

    .remark-new-component-content-pic ul {
        list-style: none;
        width: 100%;
        margin: 0;
        padding: 0;
    }

    .remark-new-component-content-pic ul li {
        list-style: none;
        float: left;
        display: inline-block;
    }

    .remark-new-component-content-pic .img {
        width: 32.333%;
        margin: 2px 0.5%;
        position: relative;
        height: 0;
        overflow: hidden;
        padding-bottom: 32.333%;
    }

    .remark-new-component-content-pic .img.hall-pic-1 {
        width: 100%;
        margin: 0;
        padding-bottom: 60%;
    }

    .remark-new-component-content-pic .img.hall-pic-2, .remark-new-component-content-pic .img.hall-pic-4, .remark-new-component-content-pic .img.hall-pic-5.imgn_0, .remark-new-component-content-pic .img.hall-pic-5.imgn_1 {
        width: 49%;
        margin: 2px 0.5%;
        padding-bottom: 49%;
    }

    .remark-new-component-content-pic .img.hall-pic-3, .remark-new-component-content-pic .img.hall-pic-6 {
        width: 32.333%;
        margin: 2px 0.5%;
        padding-bottom: 32.333%;
    }

    .remark-new-component-content-pic .img.hall-pic-5 {
        width: 32.333%;
        margin: 2px 0.5%;
        padding-bottom: 32.333%;
    }

    .remark-new-component-content-pic .img img {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        object-fit: cover;
    }

    .hall-add-more {
        color: #666666;
        text-align: center;
        font-size: 15px;
        margin-top: 25px;
        margin-bottom: 10px;
    }

    /* 输入框部分 */
    /*.edit-component-takeup {*/
    /*width: 100%;*/
    /*height: 3.8rem;*/
    /*}*/
    .edit-component-container, .edit-component-container-top {
        width: 100%;
        min-height: 2.2rem;
        margin: 0 auto;
        padding: 1.2rem 0.6rem;
        box-sizing: border-box;
        background-color: #FFFFFF;
        /*border-top: 0.06rem solid #CCCCCC;*/
        /*border-bottom: 0.06rem solid #CCCCCC;*/
    }

    .edit-component-container {
        position: fixed;
        bottom: 0;
        left: 0;
        z-index: 10000;
        background: #fff;
    }

    .edit-component-face {
        width: 12%;
        float: left;
    }

    .edit-component-face img {
        display: block;
        height: 32px;
        border-radius: 100%;
    }

    .edit-component-box {
        width: 86%;
        float: right;
        border: 1px solid #E5E5E4;
        border-radius: 0.3rem;
        line-height: 1.9rem;
        background-color: #FAFAFA;
        color: #444444;
        overflow: hidden;
    }

    .edit-component-box-img {
        width: 12%;
        float: left;
        text-align: center;
    }

    .edit-component-box-img img {
        width: 1rem;
        vertical-align: middle;
    }

    .edit-component-box-txt {
        height: 1.9rem;
        line-height: 1.9rem;
        width: 81%;
        float: left;
    }

    .edit-component-box-txt textarea {
        border: none;
        background-color: #FAFAFA;
        width: 95%;
        font-size: 1rem;
        line-height: 1.9rem;
        padding: 0 0.4rem;
        resize:none;
        margin-top: 0.1rem;
    }

    .edit-component-box-btn {
        background-color: #E5E5E4;
        height: 5.7rem;
        line-height: 5.7rem;
        width: 18%;
        text-align: center;
        font-size: 0.9rem;
        float: right;
    }

    /* 没有评论时的默认样式 */
    .remark-new-component-blank {
        margin-top: 1.0rem;
    }

    .remark-new-component-blank img {
        display: block;
        width: 45%;
        margin:0 auto;
        pointer-events:none;
    }
    .remark-new-hb{
        width: 70%;
        height:100px;
    }
    .remark-new-hb-top{
        position: relative;
        width: 100%;
        height:76px;
        box-sizing: border-box;
        padding-left: 55px;
        background: #E6494E;
        border-top-left-radius: 5px;
        border-top-right-radius: 5px;
    }
    .remark-new-hb-bottom{
        width: 100%;
        height:22px;
        border:1px solid #c2c2c2;
        border-top:0;
        box-sizing: border-box;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        color:#787878;
        font-size: 12px;
        padding-left: 10px;
        line-height: 22px;
    }
    .remark-new-hb .hb_icon{
        height:40px;
        position: absolute;
        top:18px;
        left: 8px;
    }
    .remark-new-hb .hb_disc{
        width: 85%;
        padding-top: 18px;
        height:22px;
        font-size: 18px;
        color: #ffffff;
        line-height: 22px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
    .remark-new-hb .hb_get{
        height:22px;
        line-height: 22px;
        font-size: 14px;
        color: #ffffff;
    }
    .c_orange{
        color:#E6494E
    }
    .info-org{color:#FF753F !important;}
</style>